import React, {Component} from 'react';
import Taro from '@tarojs/taro';
import {View, Text, Block} from '@tarojs/components'
import {AtIcon} from 'taro-ui';
import {
  GET_NEWS_GY_ID,
  LIMIT_FROM_SELLER_SINCE,
  INFORMATION_APP_EDIT, TARO_ENV, H5_VIDEO, CONTENT_PLAT_QR
} from '../../constants/api'
import {user} from '../../utils/user.service';
import {platform} from '../../utils/platform-settting.service';
import {http} from '../../utils/http';
import {NewsInfo} from '../../utils/server.interface';
import {getPoster} from "../../utils/poster.service";
import OtherBar from '../components/detail-bar/other-bar';
import {vcmonitor} from "../../utils/tools";
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import '../../components/liveCode/liveCode.scss'
import {getContent} from "../../utils/handlerPublicCode";
import './detail.scss';

interface NewsType {
  news: NewsInfo
  date: string
}

export default class Detail extends Component {
  state: {
    qrImg: any
    qrImgDescribe: any
    uuid: string
    news: NewsInfo
    newsDate: any
    playStatus: boolean
  } = {
    qrImg: '',
    qrImgDescribe: '',
    uuid: '',
    newsDate: '',
    playStatus: false,
    news: {
      title: '', uuid: '', content: '', author: '', view_count: 0
    }
  }

  onShareAppMessage() {
    const news = this.state.news
    if (news.share_img) {
      return {
        title: news.title,
        path: "/main/lectureRoom/detail?uuid=" + this.state.uuid + '&' + this.shareParams + `&sKey=${Taro.getStorageSync('sKey' || '')}`,
        imageUrl: news.share_img
      }
    }
    return {
      title: news.title,
      path: "/main/lectureRoom/detail?uuid=" + this.state.uuid + '&' + this.shareParams + `&sKey=${Taro.getStorageSync('sKey' || '')}`
    }
  }

  onShareTimeline() {
    const news = this.state.news
    if (news.share_img) {
      return {
        title: news.title,
        query: "uuid=" + this.state.uuid + '&' + this.shareParams + `&sKey=${Taro.getStorageSync('sKey' || '')}`,
        imageUrl: news.share_img
      }
    }
    return {
      title: news.title,
      query: "uuid=" + this.state.uuid + '&' + this.shareParams + `&sKey=${Taro.getStorageSync('sKey' || '')}`
    }
  }

  async componentDidShow() {
    vcmonitor(this)
    let uuid = ''
    const param = this.params.scene as string | undefined;
    if (param && /^\d+_\d+_\d+$/.test(param)) {
      platform.scene = 0;
      const paramArr = param.split('_'); // [ itemId, sellerId, bindSellerId, sid ] 长度不固定
      if (!paramArr[0] || !paramArr[1] || !paramArr[2]) {
        Taro.showToast({
          title: '无效的参数',
          icon: 'none'
        });
        Taro.switchTab({url: '/pages/index/index'})
        return false;
      }
      user.bindSellerId = paramArr[2]
      Taro.setStorage({
        key: 'bindSellerId',
        data: user.bindSellerId
      })
      Taro.setStorage({
        key: 'bindSellerId',
        data: user.bindSellerId,
        success: res => {
          if (user.bindSellerId) {
            Taro.login({
              success(res) {
                if (res.code) {
                  const integralForm = {
                    sellerId: user.bindSellerId,
                    code: res.code
                  }
                  http.post(LIMIT_FROM_SELLER_SINCE, integralForm);
                }
              }
            })
          }
        }
      })
      const ret = await http.get<{ uuid: string }>(GET_NEWS_GY_ID, {id: paramArr[0]})
      uuid = ret ? ret.uuid : ''
    } else {
      uuid = this.params.uuid || ''
    }
    const result: any = await http.HPost<NewsType>(INFORMATION_APP_EDIT + '/' + uuid, {})
    if (result) {
      const setting = await platform.getSetting()
      if (setting && setting.platformName) {
        Taro.setNavigationBarTitle({
          title: setting.platformName || ''
        })
      }
      if (TARO_ENV === 'h5') {
        const h5Parser: any = document.getElementById('h5Parser')
        h5Parser.innerHTML = result.data.news.content
      }
      this.setState({news: result.data.news, newsDate: result.data.date})
    }
    const res = await http.HGet(CONTENT_PLAT_QR);
    this.shareParams = await user.getSellerParams()
    if (process.env.TARO_ENV === 'h5') {
      let mpkey = ''
      const uInfo = Taro.getStorageSync('user') || ''
      if (uInfo && uInfo.mpkey && uInfo.mpkey !== 'undefined') {
        mpkey = uInfo.mpkey
      }
      await h5Wx.getConfig()
      const shareData = {
        title: result.data.news.title,
        desc: '',
        link: window.location.origin + "/main/lectureRoom/detail?uuid=" + uuid + '&mpkey=' + mpkey + '&' + this.shareParams,
        imgUrl: result.data.news.share_img
      }
      h5Wx.share(shareData)
    }
    this.setState({qrImg: res ? res.data.code : '', qrImgDescribe: res ? res.data.code_describe : '', uuid})
  }

  shareParams = ''
  params = Taro.getCurrentInstance().router.params

  async onGetPoster() {
    Taro.showLoading({title: '获取海报中...'});
    const poster = await getPoster('lecture_room', this.state.uuid || '')
    Taro.hideLoading();
    if (poster) {
      Taro.navigateTo({url: '/distributor/poster/poster?url=' + poster.url})
    } else {
      Taro.showToast({title: '获取海报失败！', icon: 'none'})
    }
  }

  play() {
    let txv = ''
    try {
      txv = Taro.requirePlugin("tencentvideo")
    } catch (e) {
      txv = ''
    }
    const TxvContext: any = txv;
    const txvContext = TxvContext && TxvContext.getTxvContext('myVideo')
    if (this.state.playStatus) {
      txvContext && txvContext.pause();
    } else {
      txvContext && txvContext.play();
    }
    this.setState({playStatus: !this.state.playStatus})
  }

  playState(s) {
    this.setState({playStatus: s})
  }

  render() {
    const {news, newsDate, playStatus, qrImg, qrImgDescribe} = this.state;
    return (
      <View className='news-root'>
        <GzhAuth />
        <View className='header'>
          <View className='title'>{news.title}</View>
          <View className='description'>
            <Text className='author'>{news.author}</Text>
            <Text className='date'>{newsDate}</Text>
          </View>
        </View>
        {news && news.qq_video_id && process.env.TARO_ENV !== 'tt' && <View className='detail-header-box'>
          {process.env.TARO_ENV != 'h5' ? <Block>
            <txv-video
              width='100vw'
              height='100%'
              controls={false}
              loop
              className='video'
              vid={news.qq_video_id}
              playerid='myVideo'
              object-fit='contain'
              isNeedMutex
              isHiddenStop
              showCenterPlayBtn={false}
              onPlay={this.playState.bind(this, true)}
              onPause={this.playState.bind(this, false)}
            />
            <View className='btn-box'>
              <View className='left'>
                {!playStatus && <AtIcon value='play' size='30' color='#FFF' onClick={this.play.bind(this)} />}
                {playStatus && <AtIcon value='pause' size='30' color='#FFF' onClick={this.play.bind(this)} />}
              </View>
            </View>
          </Block> : <Block>
            <iframe src={H5_VIDEO + news.qq_video_id} style={`height:${window.innerWidth * 0.75 + 'px'};width: 100%;`}
              allowFullScreen='true' frameBorder='0'
            />
          </Block>}
        </View>
        }
        <View className='content'>
          {process.env.TARO_ENV === 'h5' && <View id='h5Parser' />}
          {process.env.TARO_ENV === 'weapp' && <parser html={news.content || ''} />}
          {process.env.TARO_ENV === 'tt' && <rich-text preview selectable nodes={getContent(news.content)} />}
          <View className='visited'>阅读 {news.view_count}</View>
        </View>
        {news.share_img &&
          <OtherBar qrImg={qrImg} qrImgDescribe={qrImgDescribe} onGetPoster={async () => {
            await this.onGetPoster()
          }} onGotoHome={() => {
            Taro.switchTab({url: '/pages/index/index'})
          }} onContact={() => {
            Taro.navigateTo({url: `/distributor/contact/contact`})
          }}
          />}
      </View>
    );
  }
}
